clear all

current_directory = pwd;
diary parameter_search.out
parpool('local',16)
rng(17)

output_line = [];

%%% These are the target moments
growth = 3.01;
relative_wage = 1.29;
share_employment_entry = 0.144;
agg_export_revenue_share = 0.1017;
var_TFPR = 0.0116;
trade_elasticity_avg = -5;
targets = [growth;...
               growth;...
               relative_wage-1;...
               share_employment_entry;...
               agg_export_revenue_share;...
               var_TFPR;...
               trade_elasticity_avg];               

%%% These are the upper and lower bounds for the parameter estimates
%%% [lambda_US; eta_US; mu_OECD; trade_cost; theta; kappa]
%%% The last two values are kappa and nu.

lb =  [0.01;    0.01;      0.01;       1.2;        5;       0];
ub = [0.4;    0.14;      0.4;       2.5;        9;       1];

mid_bound=(lb+ub)/2;
all_distance = [];
    for repeats = 1:1:1
        x0 = [lb , (ub - lb)/6 + lb , (ub - lb)/3 + lb , (ub - lb)/2 + lb] + floor(repeats) * repmat(mid_bound,1,4);
        if max(all_distance)<1e-3
            [params_out,end_targets,prev_distance] = sim_annealing_parallel(@steady_state_simulation_search,targets,x0,ub,lb,1000);
        else
            [params_out,end_targets,prev_distance] = sim_annealing_parallel(@steady_state_simulation_search,targets,x0,ub,lb,1500);
        end
        all_distance(end+1)=prev_distance;
        output_line = [reshape(params_out(:,1),1,size(params_out,1)),reshape(end_targets,1,length(end_targets))];
          dlmwrite('parameter_estimates.csv',output_line,'-append')
    end

    
poolobj = gcp('nocreate');
delete(poolobj);

diary off
